<template>
  <div class="in-house-con table-gl-w">
    <div class="search-con search-w">
      <FilterTable :filterItem="filterItem" :isReset="true" :max-num="4" @search="searchByVal" />
    </div>

    <div class="table-gl-con">
      <TableWrap style="flex: 1" @refresh="sizeChange(20)">
        <template #headerLeft>
          <a-button class="gray-outline" size="medium" @click="show('add')" v-if="$authPass('inventory.other.in.save')">创建入库单</a-button>
        </template>
        <template #tableBody>
          <a-table class="table-two-line" ref="tableListref" :span-method="spanMethodAll" row-key="id" :expandable="expandable" :default-expand-all-rows="true" :loading="loading" :columns="tableColumns" :data="dataList" size="mini" :pagination="false" :scroll="{ x: '100%', y: '100%' }">
            <template #columns>
              <a-table-column v-for="(item, index) of tableColumns" :key="index" :width="item.width" :title="item.title" :data-index="item.dataIndex">
                <template v-if="item.dataIndex == 'shop'" #cell="{ record }">
                  <div class="flex-c-sb" style="padding-right: 20px">
                    <div class="order-w flex">
                      <div class="order-detail-item" style="width: 200px">
                        <div class="flex-c">
                          <span class="label">单号：</span>
                          <span class="highlight cursor" @click="showDetailModal(record.id)">{{ record.billNo }}</span>
                          <CopyText class="popup-edit-icon-hover" style="margin-left: 5px" :val="record.billNo" />
                        </div>
                        <p>
                          <span class="label">库仓：</span>
                          <span class="highlight">{{ record.warehouseName }}({{ record.warehouseCode }})</span>
                        </p>
                      </div>

                      <div class="order-detail-item" style="width: 200px">
                        <p><span class="label">类型：</span>其他入库</p>
                        <p><span class="label">入库数量：</span>{{ record.totalAmt }}</p>
                      </div>

                      <div class="order-detail-item" style="width: 200px">
                        <p><span class="label">创建人：</span>{{ record.createUname }}</p>
                        <p><span class="label">创建时间：</span>{{ $setTime(record.gmtCreate, 'YYYY/MM/DD HH:mm') }}</p>
                      </div>
                      <div class="order-detail-item" style="width: 200px">
                        <p><span class="label">审核人：</span>{{ record.auditorName }}</p>
                        <p><span class="label">审核时间：</span>{{ $setTime(record.gmtAudit, 'YYYY/MM/DD HH:mm') }}</p>
                      </div>
                      <div class="order-detail-item" style="width: 140px">
                        <p><span class="label">总货值：</span>{{ record.totalValue }}</p>
                        <p><span class="label">状态：</span>{{ statusMap[record.status] }}</p>
                      </div>
                      <div class="order-detail-item" style="width: 140px">
                        <TextLimit :val="'备注：' + record.remark" :rows="1" />
                        <TextLimit :val="record.auditRemark" :rows="1" />
                      </div>
                    </div>
                    <div class="flex-c">
                      <a-button type="text" class="ml10" @click="showDetailModal(record.id)">详情</a-button>
                      <a-button type="text" class="ml10" @click="toAudit(record, 2)" v-if="record.status == 2 && $authPass('inventory.other.in.audit')">审核</a-button>
                      <a-button type="text" class="ml10" @click="toAudit(record, 1)" v-if="(record.status == 1 || record.status == 4) && $authPass('inventory.other.in.audit')">提交审核</a-button>
                      <a-button type="text" class="ml10" v-if="(record.status == 1 || record.status == 4) && $authPass('inventory.other.in.edit')" @click="show('edit', record.id)">编辑</a-button>
                      <a-button type="text" class="ml10" v-if="(record.status == 1 || record.status == 4) && $authPass('inventory.other.in.delete')" style="color: red" @click="del(record)">删除</a-button>
                    </div>
                  </div>
                </template>
              </a-table-column>
            </template>
            <template #expand-row="{ record }">
              <a-table :show-header="false" row-key="id" :bordered="false" :columns="tableColumns" :data="record.otherInItems" :pagination="false">
                <template #columns>
                  <a-table-column :width="10" />
                  <!-- <a-table-column :width="50" /> -->
                  <a-table-column v-for="(item, index) of tableColumns" :key="index" :fixed="item.fixed" :align="item.align" :width="item.width" :title="item.title" :data-index="item.dataIndex">
                    <template v-if="item.dataIndex == 'shop'" #cell="{ record }">
                      {{ record.shopName }}
                    </template>
                    <template v-else-if="item.dataIndex == 'img'" #cell="{ record }">
                      <ImgPopover :src="record.productImg">
                        <template #con>
                          <a-image style="margin-top: 8px" width="40px" height="40px" :src="record.productImg" />
                        </template>
                      </ImgPopover>
                    </template>
                    <template v-else-if="item.dataIndex == 'sku'" #cell="{ record }">
                      <TextLimit :val="record.productName ? record.productName : '--'" :rows="1" />
                      <ShowSpuDetailBySku :val="record.sku ? record.sku : '--'" :showLimit="true" :rows="1" />
                    </template>
                    <template v-else-if="item.dataIndex == 'msku'" #cell="{ record }">
                      <TextLimit :val="record.msku" :rows="1" />
                    </template>
                    <template v-else-if="item.dataIndex == 'spu'" #cell="{ record }">
                      <TextLimit :val="record.spu ? record.spu : '--'" :rows="1" />
                      <div>{{ record.cateName ? record.cateName : '--' }}</div>
                    </template>
                    <template v-else-if="item.dataIndex == 'brand'" #cell="{ record }">
                      <div>{{ record.brandName ? record.brandName : '--' }}</div>
                    </template>
                    <template v-else-if="item.dataIndex == 'categoryType'" #cell="{ record }">
                      <div>{{ record.productType }}</div>
                    </template>
                    <template v-else-if="item.dataIndex == 'num'" #cell="{ record }">
                      <div>{{ record.amt }}</div>
                    </template>
                    <template v-else-if="item.dataIndex == 'inventoryProperty'" #cell="{ record }">
                      {{ record.attribute == 'good' ? '良品' : '次品' }}
                    </template>
                    <template v-else-if="item.dataIndex == 'unitCost'" #cell="{ record }">
                      {{ record.price }}
                    </template>
                    <template v-else-if="item.dataIndex == 'price'" #cell="{ record }">
                      <!-- {{ record.price * record.amt }} -->
                      {{ record.value }}
                    </template>
                    <template v-else-if="item.dataIndex == 'shelfSpace'" #cell="{ record }">
                      {{ record.locationCode }}
                    </template>
                  </a-table-column>
                </template>
              </a-table>
            </template>
          </a-table>
        </template>
      </TableWrap>
      <div class="pagination-footer">
        <a-pagination size="mini" :page-size-options="[20, 50, 100, 200, 500]" show-total show-page-size :total="pageNation.total" :default-page-size="pageNation.pageSize" :current="pageNation.pageNum" style="float: right" @page-size-change="sizeChange" @change="changePage" />
      </div>
    </div>
  </div>
  <Detatil ref="detail" :type="detailType" :id="id" @save="sizeChange(20)" />
  <Audit ref="audit" :info="info" @save="getList" />
  <ShowDetail ref="showDetail" :id="id" type="in" />
</template>

<script lang="ts">
  import { defineComponent, reactive, ref, toRefs } from 'vue'
  import FilterTable from '@/components/TableFilter.vue'
  import TableWrap from '@/components/TableWrap.vue'
  import Detatil from './components/createdInHouse.vue'
  import ShowDetail from './components/showDetail.vue'
  import { findOtherInPageByParam, commitOtherIn, findShopListByShare, deleteOtherIn } from '@/api/warehouse'
  import Audit from './components/audit.vue'
  import { Modal, Message } from '@arco-design/web-vue'
  import _ from 'lodash-es'
  import useClipboard from 'vue-clipboard3'
  import { getOrganizesUser } from '@/api/system'
  export default defineComponent({
    name: 'InHouse',
    components: { FilterTable, TableWrap, Detatil, Audit, ShowDetail },

    setup() {
      const detail = ref()
      const audit = ref()
      const { toClipboard } = useClipboard()
      const showDetail = ref()
      const data: any = reactive({
        statusMap: {
          1: '草稿',
          2: '待审核',
          3: '完成',
          4: '驳回',
        },
        filterItem: [
          {
            type: 'input_keyword',
            key: 'warehouseName',
            keyItems: [
              { label: '仓库名称', value: 'warehouseName' },
              { label: '仓库ID', value: 'warehouseCode' },
            ],
            keyWidth: '90',
            value: ref(),
            placeholder: '请输入',
            label: '仓库名称',
            width: 160,
            isMultiple: false,
          },
          {
            type: 'input_search',
            label: '单号',
            key: 'billNo',
            value: ref(),
            placeholder: '请输入单号',
            width: 160,
            isMultiple: false,
          },
          {
            key: 'shopId',
            label: '店铺',
            value: ref(),
            type: 'select_multiple',
            width: 140,
            optionItems: [],
            attrs: {
              multiple: true,
              'max-tag-count': 1,
            },
          },
          {
            key: 'ownerIds',
            label: '选择货主',
            value: ref(),
            type: 'select_multiple',
            width: 160,
            optionItems: [],
          },
          {
            type: 'input_keyword',
            key: 'skus',
            keyItems: [
              { label: 'SKU', value: 'skus' },
              { label: 'SPU', value: 'spus' },
              { label: 'MSKU', value: 'mskus' },
              { label: 'FNSKU', value: 'fnskus' },
              { label: '产品名称', value: 'productName' },
            ],
            keyWidth: '110',
            value: ref(),
            placeholder: '请输入',
            label: 'SKU',
            width: 300,
            isMultiple: true,
          },
          {
            type: 'sel_double',
            key: 'createUid',
            keyItems: [
              { label: '创建人', value: 'createUid' },
              { label: '审核人', value: 'auditorId' },
            ],
            keyWidth: '110',
            optionItems: [],
            value: ref(),
            placeholder: '请输入',
            label: '创建人',
            width: '100%',
            isMultiple: false,
          },
          {
            type: 'keyword_date_range',
            key: 'gmtCreate',
            keyItems: [
              { label: '创建日期', value: 'gmtCreate' },
              { label: '审核日期', value: 'gmtAudit' },
            ],
            keyWidth: '110',
            value: ref(),
            placeholder: '请输入',
            label: '创建日期',
            width: 300,
          },
          {
            key: 'status',
            label: '状态',
            value: ref(),
            type: 'select',
            width: 410,
            optionItems: [
              {
                label: '状态',
                value: '',
              },
              {
                label: '待审核',
                value: '2',
              },
              {
                label: '已完成',
                value: '3',
              },
              {
                label: '已驳回',
                value: '4',
              },
            ],
          },
        ],
        tableColumns: [
          { title: '店铺', dataIndex: 'shop', width: 80 },
          { title: '货主', dataIndex: 'ownerName', width: 70 },
          { title: '图片', dataIndex: 'img', width: 50 },
          { title: '产品名称/SKU', dataIndex: 'sku', width: 100 },
          { title: 'MSKU', dataIndex: 'msku', width: 100 },
          { title: 'SPU/类目', dataIndex: 'spu', width: 100 },
          { title: '品牌', dataIndex: 'brand', width: 80 },
          // { title: '单位', dataIndex: 'name', width: 120 },
          { title: '产品类型', dataIndex: 'categoryType', width: 100 },
          { title: '数量', dataIndex: 'num', width: 100 },
          { title: '库存属性', dataIndex: 'inventoryProperty', width: 100 },
          { title: '单位成本', dataIndex: 'unitCost', width: 100 },
          { title: '货值', dataIndex: 'price', width: 100 },
          { title: '上架货位', dataIndex: 'shelfSpace', width: 100 },
        ],
        dataList: [],
        pageNation: { total: 0, pageSize: 20, pageNum: 1 },
        // expandable: {},
        loading: false,
        isCollapse: false,
        info: {
          type: 'in',
          id: '',
        },
        id: '',
        detailType: '',
        searchValue: {},
        isShowDetail: false,
        expandable: {
          title: '',
          defaultExpandAllRows: true,
          expandedRowKeys: [],
          width: 10,
        },
      })
      const searchByVal = (info: any) => {
        data.searchValue = {}
        data.searchValue = info
        data.pageNation.pageNum = 1
        if (data.searchValue.startDate) {
          data.searchValue.startDate = `${data.searchValue.startDate} 00:00:00`
          data.searchValue.endDate = `${data.searchValue.endDate} 23:59:59`
        }

        getList()
      }
      const changePage = (val: number) => {
        data.pageNation.pageNum = val
        getList()
      }

      const sizeChange = (val: number) => {
        data.pageNation.pageNum = 1
        data.pageNation.pageSize = val
        getList()
      }
      const changeAll = (val: boolean) => {
        data.dataList.map((e: any) => (e.checked = val))
      }

      const getList = async (info?: any) => {
        let params = {
          ...data.searchValue,
          pageNum: data.pageNation.pageNum,
          pageSize: data.pageNation.pageSize,
        }
        data.isCollapse = false
        data.loading = true
        const res = await findOtherInPageByParam(params)
        data.dataList = res.data?.records || []
        data.pageNation.total = res.data?.total
        data.expandable.expandedRowKeys = data.dataList.map((el: any) => el.id)
        data.loading = false
      }

      const collapseAll = (val: boolean) => {
        data.isCollapse = val
        data.dataList.map((e: any) => (e.isCollapse = val))
      }

      const toAudit = (item: any, type: number) => {
        if (type == 2) {
          data.info.id = item.id
          data.info.type = 'in'
          audit.value.visible = true
        } else if (type == 1) {
          Modal.error({
            title: '提示',
            content: '是否提交审核？',
            titleAlign: 'start',
            cancelText: '取消',
            hideCancel: false,
            onBeforeOk: async (done) => {
              const res: any = await commitOtherIn({ ids: [item.id] })
              if (res.code == 'SUCCESS') {
                done(true)
                Message.success('提交成功')
                getList()
              }
            },
          })
        }
      }

      const showDetailModal = (id: string) => {
        data.id = id
        showDetail.value.visible = true
      }

      const copy = async (val: string) => {
        try {
          // 复制
          await toClipboard(val)
          Message.success('复制成功')
          // 复制成功
        } catch (e) {
          // 复制失败
        }
      }

      // 获取店铺列表
      const getShopList = async () => {
        const res = await findShopListByShare()
        let arr = res?.data.map((e: any) => {
          e.label = e.shopName
          e.value = e.sellerMarketId
          return e
        })
        data.filterItem[2].optionItems = arr || []
      }

      // 获取用户列表
      const getUSerList = async () => {
        let params = {
          depart: false,
          pageNum: 1,
          pageSize: 1000,
        }
        const res: any = await getOrganizesUser(params)
        if (res.code == 'SUCCESS') {
          let userList = res.data.records
          userList.map((e: any) => {
            e.label = e.userName
            e.value = e.id
            return e
          })
          data.filterItem[3].optionItems = userList
        }
      }

      const del = (item: any) => {
        Modal.confirm({
          title: '删除',
          content: `请再次确认是否删除入库单`,
          cancelText: '取消',
          okText: '确认',
          titleAlign: 'start',
          onOk: async () => {
            const res: any = await deleteOtherIn({ ids: [item.id] })
            if (res) {
              Message.success('删除成功')
              getList()
            }
          },
        })
      }

      const show = (type: string, id: string) => {
        data.detailType = type
        data.id = id
        detail.value.visible = true
      }

      // 合并单元格
      function spanMethodAll(option: any) {
        let { column } = option
        if (column.dataIndex === 'shop') {
          return { rowspan: 1, colspan: 13 }
        }
      }

      getShopList()
      getList()
      getUSerList()
      return {
        ...(toRefs(data) as any),
        searchByVal,
        changePage,
        sizeChange,
        changeAll,
        collapseAll,
        detail,
        audit,
        toAudit,
        getList,
        showDetail,
        showDetailModal,
        copy,
        del,
        show,
        spanMethodAll,
      }
    },
  })
</script>

<style lang="less" scoped>
  :deep(.arco-table-td) {
    background-color: var(--color-fill-1);
  }
  :deep(.arco-table-tr-expand) {
    .arco-table-cell {
      padding: 0;
    }
    .arco-table {
      margin: 0 !important;
      .arco-table-td {
        border-bottom: 1px solid var(--color-neutral-3);
      }
    }
    background-color: #fff !important;
  }
  :deep(.child-row) {
    .arco-table-cell {
      padding: 2px 8px;
    }
  }
  :deep(.arco-table-tr-expand .arco-table-td) {
    background-color: #fff !important;
    border-bottom: none;
  }
  :deep(.arco-table-tr-expand tr:hover .arco-table-td) {
    background-color: var(--color-fill-1) !important;
  }
  :deep(.arco-table-expand .arco-table-cell) {
    display: none;
  }
  :deep(.arco-tabs-nav-tab) {
    background-color: #fff;
  }
  .order-w {
    color: #666;
    flex: 1;
    .order-detail-item {
      width: 200px;
    }
  }

  .icon-btn {
    font-size: 18px;
    text-align: center;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    cursor: pointer;
  }

  .arco-scrollbar-type-embed,
  .arco-scrollbar-both {
    width: 100% !important;
    height: calc(100% - 37px) !important;
  }

  .in-house-con {
    width: 100%;
    height: calc(100vh - @menuAndTabHeight);
    // background-color: white;
  }

  .search-con {
    // padding: 10px;
    box-sizing: border-box;
  }

  .line {
    width: 100%;
    height: 5px;
    background-color: #f0f2f5;
  }

  .label {
    // color: #9ca4ae;
  }

  .my-table {
    width: 100%;
    min-height: 37px;
    text-align: left;
    font-size: 12px;
    background-color: #f2f3f5;
    line-height: 37px;
  }

  .item {
    width: 100%;
    height: 80px;
    border-bottom: 1px solid #e5e6eb;
    // display: flex;
    font-size: 12px;
    overflow: hidden;
    position: relative;

    &::-webkit-scrollbar {
      height: 6px;
      position: absolute;
      bottom: 0;
    }

    &:hover {
      overflow: auto;
    }

    &::-webkit-scrollbar-thumb {
      border-radius: 10px;
      -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
      opacity: 0.2;
      background: #d4d7dd;
    }

    &::-webkit-scrollbar-track {
      // -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
      border-radius: 10px;
      background: white;
      opacity: 0;
    }

    .item-con {
      min-width: 1480px;
    }

    .left {
      width: 80px;
      height: 62px;
      position: relative;
      float: left;
    }
    .right {
      height: 68px;
      width: calc(100% - 80px);
      display: flex;

      .right-box {
        float: left;
        user-select: none;
        width: 200px;

        .hd,
        .bd {
          width: 100%;
          height: 31px;
          line-height: 31px;
        }
        .btn {
          color: #169bd5;
          cursor: pointer;
          user-select: none;
          display: inline-block;
        }
      }
    }
  }

  .tbody-con {
    // width: 100%;
    // height: 100%;
    text-align: left;
    table-layout: fixed;
    tr {
      &:nth-child(1) {
      }
      td {
        height: 56px;
        box-sizing: border-box;
        // border-right: 1px solid #e5e6eb;
      }
    }
  }
</style>
